package com.acc.sys.service;

import apijson.RequestMethod;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.acc.config.UploadConfig;
import com.acc.sys.framework.AccParser;
import com.acc.utils.DbUtil;
import com.alibaba.fastjson.JSONObject;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.Objects;
import java.util.UUID;

import static com.acc.sys.constants.TableNameConstants.SYS_FILE;

/**
 * 文件上传
 */
@Service
@Slf4j
@AllArgsConstructor
public class UploadService {

    private UploadManager uploadManager;
    private Auth auth;
    private UploadConfig uploadConfig;

    public JSONObject upload(MultipartFile multipartFile) {
        long size = multipartFile.getSize();//文件大小
        String type = multipartFile.getContentType();//文件类型
        String originalName = multipartFile.getOriginalFilename();//文件名称
        String fileSuffix = Objects.requireNonNull(multipartFile.getOriginalFilename()).substring(multipartFile.getOriginalFilename().lastIndexOf("."));//文件后缀

        String filename = UUID.randomUUID() + fileSuffix;
        String url = StrUtil.format("upload/{}/{}", DateUtil.format(new Date(), "yyyy/MMdd"), filename);
        String token = auth.uploadToken(uploadConfig.getBucketName());
        Response res;
        try {
            res = uploadManager.put(multipartFile.getInputStream(), url, token, null, null);
        } catch (IOException e) {
            throw new RuntimeException("文件上传错误:" + e.getMessage());
        }
        if (!res.isOK()) {
            throw new RuntimeException("上传七牛云出错:" + res);
        }
        JSONObject fileObj = new JSONObject();
        fileObj.put("size", size);
        fileObj.put("type", type);
        fileObj.put("original_name", originalName);
        fileObj.put("file_name", filename);
        fileObj.put("file_suffix", fileSuffix);
        fileObj.put("url", url);
        DbUtil.table(SYS_FILE).save(fileObj, RequestMethod.POST);
        return fileObj;
    }

}
